<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>跑跑特工</title>
    <!-- 引入样式文件 -->
    <link rel="stylesheet" href="./utils/vant.css" />
    <!-- 引入 Vue 和 Vant 的 JS 文件 -->
    <script src="./utils/vue.js"></script>
    <script src="./utils/vant.js"></script>
    <!-- 引入axios（如果sendData是基于axios的） -->
    <script src="./utils/axios.js"></script>
    <!-- 调用JS接口的页面引入如下JS文件 -->
    <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <!-- 自定义样式 -->
    <style>
        body {
            background-color: #f7f7f7;
        }

        .top {
            width: 100%;
            height: 32px;
            text-align: center;
            line-height: 32px;
        }

        .mt15 {
            margin-top: 30px;
        }

        .m16 {
            margin: 16px;
        }

        .tips {
            margin-top: 30px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="top">授权网站:https://www.yjercf.buzz/zhiyinsq/#/bdlp</div>
        <div class="top container" style="color: red;">每次使用必须授权，这个网站必须用浏览器打开！！！(最好用电脑)</div>
        <div class="mt15">
            <van-form ref="formRef">
                <van-cell-group inset>
                    <!-- id -->
                    <van-field v-model="data.userId" name="乐跑id" label="乐跑id" placeholder="请输入您的乐跑id"
                        :rules="rules.userId"></van-field>
                    <!-- timer -->
                    <van-field v-model="data.times" is-link readonly label="乐跑次数" placeholder="点击选择次数"
                        @click="showTimes = true" :rules="rules.times"></van-field>
                    <van-action-sheet v-model:show="showTimes" :actions="actions" close-on-click-action
                        @select="(item) => (data.times = item.name)"></van-action-sheet>
                    <!-- km -->
                    <van-field name="radio" label="乐跑公里数">
                        <template #input>
                            <van-radio-group v-model="data.km" direction="horizontal">
                                <van-radio name="1">1公里</van-radio>
                                <van-radio name="3">3公里</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                    <!-- time -->
                    <van-field v-model="data.startDate" is-link readonly name="calendar" label="开始时间"
                        placeholder="点击选择日期" @click="showCalendar = true" :rules="rules.startDate"></van-field>
                    <van-calendar v-model:show="showCalendar" @confirm="confirmDate"></van-calendar>
                </van-cell-group>
                <div class="m16">
                    <van-button round block type="primary" native-type="submit" @click="submit">
                        下单
                    </van-button>
                </div>

            </van-form>
        </div>
        <!-- 底层标签页 -->
        <van-tabbar class="tabbar" v-model="active" @change="onChange">
            <van-tabbar-item icon="wap-home" name="index">主页</van-tabbar-item>
            <van-tabbar-item icon="bars" name="order">订单</van-tabbar-item>
        </van-tabbar>
    </div>

</body>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                active: 'index',
                actions: Array.from({ length: 7 }, (_, index) => ({
                    name: `${index + 1}`
                })),
                rules: {
                    userId: [
                        { required: true, message: "请填写乐跑id" },
                        { validator: (val) => /^\d{8}$/.test(val), message: "乐跑id必须是的八位数字" },
                    ],
                    times: [{ required: true, message: "请选择次数" }],
                    startDate: [{ required: true, message: "请选择日期" }],
                },
                data: {
                    userId: "",
                    times: "",
                    km: "1",
                    startDate: "",
                    amount: ""
                },
                formRef: null,
                showCalendar: false,
                showTimes: false,
                wxdata: {},
                shuju: {}
            };
        },
        methods: {
            //获取日期实例
            formatDate(startDate) {
                return startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate();
            },
            //日期确认按钮
            confirmDate(startDate) {
                this.data.startDate = this.formatDate(startDate);
                this.showCalendar = false;
            },
            //计算总额
            totalAmount() {
                this.data.amount = ((this.data.km === '1' ? 1.5 : 2.5) * this.data.times) * 100
            },
            //下单按钮
            async submit() {
                this.totalAmount()
                await this.$refs.formRef?.validate();
                const result = await axios({
                    method: 'POST',
                    url: 'http://71hi31ml3628.vicp.fun/order/insert',
                    data: this.data,
                    headers: {
                        'Token': `${localStorage.getItem('lptoken')}`
                    }
                })
                if (result.data.code === 1) {
                    localStorage.setItem('wxdata', JSON.stringify(result.data.data))
                    localStorage.setItem('data', JSON.stringify(this.data));
                    location.href = './pay.html'
                } else {
                    this.$notify({ type: 'danger', message: '提交失败' })
                }
            },
            //标签页切换
            onChange(index) {
                location.href = `./${index}.html`
            },
            // 获取路径上的token参数
            GetQueryString(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
                var r = window.location.search.substring(1).match(reg)
                if (r != null) {
                    return decodeURIComponent(r[2])
                }
                return ''
            },
            demo() {
                let _this = this
                //通过config接口注入权限验证配置
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: 'wx564d88ff17b07255', // 必填，公众号的唯一标识
                    timestamp: 1730281203, // 必填，生成签名的时间戳
                    nonceStr: 'ec54de9b5b054674b845d1efe7a15934', // 必填，生成签名的随机串
                    signature: 'qP5BfxFk7eoMxHGgZQOITIBhBZJviQ4QpWcvXJk8bRIG0GktWwVM+lQljWCMVDLFKCOJfzqZmUumBN8CfnFBlau79/4+CdT5NcFPno9GikrKjI6l8HlJmhiMpT3R8fvJeHwTkJwCWEJG1ACpBheD3WIAIPPlIjopRbvz/lMZn9CmV4uRECMimqsg4AZ0V2hxDN3hbFAcm1iK9I/zfe4GVJKa9J2s08qWrt55xSkC8GDvLWPEKm9/6CoKmrzhId/XKg25u4f54nmoW40DHMV1U8xw9MeSsTi6H/uyjH5LOW+CVtWmeYREibh9fmtg8cmJKCi1DUvh3C85ahhw1clj/A==',// 必填，签名
                    jsApiList: ['checkJsApi', 'getLocation'] // 必填，需要使用的JS接口列表
                })
                // 处理成功后回调
                wx.ready(function () {
                    wx.getLocation({
                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                        success: function (res) {
                            _this.shuju = res
                            alert(_this.shuju)
                            // var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                            // var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                            // var speed = res.speed; // 速度，以米/每秒计
                            // var accuracy = res.accuracy; // 位置精度
                            // console.log(_this.shuju);
                            
                        },
                        fail: function (err) {
                            alert("获取定位位置信息失败！")
                        },
                        cancel: function (res) {
                            alert('用户拒绝授权获取地理位置');
                        }
                    });
                });
                // 处理失败后回调
                wx.error(function (err) {
                    console.log("处理失败:", err);
                });
            }
        },
        async mounted() {
            const token = this.GetQueryString('token')
            if (!token) {
                if (!localStorage.getItem('lptoken')) {
                    // 重定向到微信的 OAuth 授权页面 
                    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx564d88ff17b07255&redirect_uri=http%3a%2f%2f71hi31ml3628.vicp.fun%2fuser%2flogin&response_type=code&scope=snsapi_userinfo#wechat_redirect'
                } else {
                    // 如果 localStorage 中有 token，则无需任何操作（或进行其他初始化操作）
                }
            } else {
                // 如果 URL 中有 token，可以选择性地将其存储到 localStorage 中（如果需要的话）  
                localStorage.setItem('lptoken', token)
            }
            this.demo()
        }
    })
</script>

</html>